package com.qf.shixi.config;

import com.alibaba.fastjson.JSONObject;
import com.qf.shixi.entity.SysUser;
import com.qf.shixi.result.ResponseCode;
import com.qf.shixi.result.ResponseData;
import com.qf.shixi.service.SysUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


@Component
public class AuthorizedInterceptor implements HandlerInterceptor {
    Logger logger = LoggerFactory.getLogger(AuthorizedInterceptor.class);

    // 释放的路径白名单
    public static final String[] noAuthorizes = {
            "/sysUser/login",
            "/swagger-ui.html",
            "/webjars/springfox-swagger-ui/springfox.css",
            "/webjars/springfox-swagger-ui/swagger-ui.css",
            "/webjars/springfox-swagger-ui/swagger-ui-bundle.js",
            "/webjars/springfox-swagger-ui/springfox.js",
            "/webjars/springfox-swagger-ui/swagger-ui-standalone-preset.js",
            "/webjars/springfox-swagger-ui/favicon-32x32.png",
            "/webjars/springfox-swagger-ui/favicon-16x16.png",
            "/swagger-resources/configuration/ui",
            "/swagger-resources/configuration/security",
            "/swagger-resources",
            "/api/",
            ".png",
            ".jpg"
    };

    public static final String APIUPDATE = "/sysUser/api/update";

    public static final String APIINSERT = "/sysUser/api/insert";




    @Autowired
    private SysUserService sysUserService;


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //拦截当前请求  http://localhost:8080/    sysUser/login   url    urI
        String requestURI = request.getRequestURI();
        logger.info("本次请求为:"+requestURI);
        //判断当前请求是否直接放行
        for (String noAuthorize : noAuthorizes) {
            if(requestURI.contains(noAuthorize) && !requestURI.contains(APIINSERT) && !requestURI.contains(APIUPDATE)){
                return true;
            }
        }

        // 跨域的预检请求 OPTIONS  options  Option    类型需要放行
        String method = request.getMethod();
        if(method.equalsIgnoreCase("OPTIONS")){
            return true;
        }

        String token = null;
        SysUser sysUser = null;
//        微信小程序和PC传递token的方法不一致  微信采用head传递token   pc端采用cookie传递token
        if(requestURI.contains(APIINSERT) || requestURI.contains(APIUPDATE) ){
            token = request.getHeader("token");
            logger.info("微信小程序端请求token为:"+token);
            sysUser =  sysUserService.queryByToken(token);
        }else{
            // 获取cookie  key-value     token: ""
            Cookie[] cookies = request.getCookies();
            if(cookies != null && cookies.length != 0){
                for (Cookie cookie : cookies) {
                    if( cookie.getName().equals("token")){
                        token = cookie.getValue();
                    }
                }
                sysUser =  sysUserService.queryBySysToken(token);
            } else {
                sysUser =  sysUserService.queryBySysToken(token);
            }
        }

        //链接redis,去找token是否过期 (去数据库中找对应的token是否存在)

        if(sysUser == null){
            //说明当前token过期,拒绝访问
            ResponseData responseData = new ResponseData(ResponseCode.USERINFO_EXCEPTION.getCode(), ResponseCode.USERINFO_EXCEPTION.getMessage());
            String s = JSONObject.toJSONString(responseData);
            response.setContentType("text/html;charset=UTF-8");
            response.getWriter().write(s);
            response.getWriter().flush();
            response.getWriter().close();
            return false;
        }
        return true;
    }


}
